package com.crime.crimemonitorclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpStatus;

import android.os.AsyncTask;

import com.crimemonitor.library.CrimeSummaryDetailed;
import com.crimemonitor.library.CrimesSummary;
import com.google.gson.Gson;

public class GetCrimeDetailAsyncTask extends AsyncTask<Void, Void, CrimeSummaryDetailed> {

	private Exception mException;
	private final String serviceURL;
	private final int tsk;
	private final int startYear;
	private final int startMonth;
	private final int endYear;
	private final int endMonth;
	private final OnCrimeDetailLoaded mCrimeDetailedSummaryLoadedHandler;
	
	public GetCrimeDetailAsyncTask(
			String serviceURL,
			int tsk,
			int startYear,
			int startMonth,
			int endYear,
			int endMonth,
			OnCrimeDetailLoaded loadedHandler)
	{
		this.serviceURL = serviceURL;
		this.tsk = tsk;
		this.startYear = startYear;
		this.startMonth = startMonth;
		this.endYear = endYear;
		this.endMonth= endMonth;
		this.mCrimeDetailedSummaryLoadedHandler = loadedHandler;
	}
	
	@Override
	protected CrimeSummaryDetailed doInBackground(Void... args) {
		
		HttpURLConnection conn = null;
		BufferedReader isReader = null;
		
		try {
			URL serviceURL = new URL(
					String.format("%s/%d/?startYear=%d&startMonth=%d&endYear=%d&endMonth=%d",
							this.serviceURL,
							this.tsk,
							this.startYear, this.startMonth,
							this.endYear, this.endMonth));
			
			conn = (HttpURLConnection)serviceURL.openConnection();
			isReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			if(conn.getResponseCode() == HttpStatus.SC_OK)
			{
				StringBuilder sb = new StringBuilder();
				String readLine;
				while((readLine = isReader.readLine()) != null)
				{
					sb.append(readLine);
					sb.append("\n");
				}
				
				return new Gson().fromJson(sb.toString(), CrimeSummaryDetailed.class);
			}
			else
			{
				this.mException = new IOException(conn.getResponseMessage());
			}
		}
		catch (Exception e)
		{
			this.mException = e;
		}
		finally
		{
			if(conn != null)
				conn.disconnect();
			
			if(isReader != null)
			{
				try
				{
					isReader.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(CrimeSummaryDetailed result) {
		super.onPostExecute(result);
		
		if(this.mCrimeDetailedSummaryLoadedHandler != null)
		{
			this.mCrimeDetailedSummaryLoadedHandler.onCrimeDetailLoaded(result);
		}
	}
}